package co.fitstart.mobile.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.support.Page;

import co.fitstart.entity.credit.Credit;
import co.fitstart.entity.credit.product.CreditProduct;
import co.fitstart.entity.credit.product.CreditProductTag;
import co.fitstart.entity.user.User;
import co.fitstart.mobile.dao.support.CreditDaoSupport;
import co.fitstart.mobile.dao.support.CreditMallDaoSupport;
import co.fitstart.mobile.service.CreditMallService;

/**
 * @author Guangli Yan
 *
 */
@Service("creditMallService")
public class CreditMallServiceImpl implements CreditMallService {

    @Autowired
    private CreditMallDaoSupport creditMallDaoSupport;

    @Autowired
    private CreditDaoSupport creditDaoSupport;

    /*
     * (non-Javadoc)
     * 
     * @see
     * co.fitstart.mobile.service.CreditMallService#listCreditProduction(co.
     * fitstart.entity.credit.product.CreditProductTag)
     */
    public List<CreditProduct> listCreditProduction(CreditProductTag creditProductTag) {

        List<CreditProduct> creditProducts = creditMallDaoSupport.list(creditProductTag);

        if (!CollectionUtils.isEmpty(creditProducts) && creditProducts.size() > 4) {
            creditProducts = creditProducts.subList(0, 4);
        }

        return creditProducts;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * co.fitstart.mobile.service.CreditMallService#listCreditProduction(co.
     * fitstart.entity.credit.product.CreditProductTag,
     * com.demo2do.core.support.Page)
     */
    public List<CreditProduct> listCreditProduction(CreditProductTag tab, Page page) {

        List<CreditProduct> result = creditMallDaoSupport.list(tab, page);

        page.calculate(result.size());

        return result.size() > page.getEveryPage() ? result.subList(0, page.getEveryPage()) : result;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * co.fitstart.mobile.service.CreditMallService#calculateMaxExchangeNum(co.
     * fitstart.entity.credit.product.CreditProduct,
     * co.fitstart.entity.user.User)
     */
    public int calculateMaxExchangeNum(CreditProduct creditProduct, User user) {
        int currentPrice = creditProduct.getCurrentPrice().intValue();
        Credit credit = creditDaoSupport.generallyLoad(user);

        if (credit == null) {
            return 0;
        } else {
            int creditNum = credit.getAvailableCredit();

            return creditNum / currentPrice;
        }
    }

}
